package com.itheima.service;

import com.itheima.mapper.BrandMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * @author : sky
 * @date : 2023/4/21 7:42
 * @modyified By :
 */

public class UserService {
/**用户登陆方法
 * @Param username,password
 * @return  User
 * */
public User login(String username, String password) {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    //2. 获取SqlSession
    SqlSession sqlSession = factory.openSession();
    //3. 获取BrandMapper
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    //调用方法
    User user = mapper.select(username, password);
    //关闭流
    sqlSession.close();
        return user;
}

/** 用户注册方法
 * @Param username
 * @return
  * */
public boolean register(User user){
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    //2. 获取SqlSession
    SqlSession sqlSession = factory.openSession();
    //3. 获取BrandMapper
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User u = mapper.selectByUsername(user.getUsername());
    //判断用户是否存在
    if (u == null ){
        //用户名不存在，添加用户
        mapper.add(user);
        //提交事务
        sqlSession.commit();
        //关闭流
        sqlSession.close();
        return true;
            }else {
        //用户名存在，返回false
        return false;
    }

}
}
